package com.uchengwang.ui.cm_ui.rychat.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.cm_ui.login.LoginHttp.LoginHttpManager;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.rychat.bean.ContactNotificationMessageData;
import com.uchengwang.ui.cm_ui.cycle.bean.RyGroupBean;
import com.uchengwang.ui.cm_ui.rychat.config.SealExtensionModule;
import com.uchengwang.ui.cm_ui.rychat.manager.SealUserInfoManager;
import com.uchengwang.ui.cm_ui.umsg.ui.WantChatPersonInfoActivity;
import com.uchengwang.ui.cm_ui.umsg.ui.WantMeActivity;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.List;

import io.rong.imkit.DefaultExtensionModule;
import io.rong.imkit.IExtensionModule;
import io.rong.imkit.RongExtensionManager;
import io.rong.imkit.RongIM;
import io.rong.imkit.model.GroupUserInfo;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ContactNotificationMessage;
import io.rong.message.ImageMessage;

/**
 * 融云相关监听 事件集合类
 * Created by AMing on 16/1/7.
 * Company RongCloud
 */
public class SealAppContext implements RongIM.ConversationListBehaviorListener,
        RongIMClient.OnReceiveMessageListener,
        RongIM.UserInfoProvider,
        RongIM.GroupInfoProvider,
        RongIM.GroupUserInfoProvider,
        RongIM.LocationProvider,
        RongIM.ConversationBehaviorListener,
        RongIM.IGroupMembersProvider {


    private Context mContext;

    private static SealAppContext mRongCloudInstance;


    public SealAppContext(Context mContext) {
        this.mContext = mContext;
        initListener();
        SealUserInfoManager.init(mContext);
    }

    /**
     * 初始化 RongCloud.
     *
     * @param context 上下文。
     */
    public static void init(Context context) {

        if (mRongCloudInstance == null) {
            synchronized (SealAppContext.class) {

                if (mRongCloudInstance == null) {
                    mRongCloudInstance = new SealAppContext(context);
                }
            }
        }

    }

    /**
     * 获取RongCloud 实例。
     *
     * @return RongCloud。
     */
    public static SealAppContext getInstance() {
        return mRongCloudInstance;
    }

    public Context getContext() {
        return mContext;
    }


    /**
     * init 后就能设置的监听
     */
    private void initListener() {
        RongIM.setConversationBehaviorListener(this);//设置会话界面操作的监听器。
        RongIM.setConversationListBehaviorListener(this);
        RongIM.setUserInfoProvider(this, true);
        RongIM.setGroupInfoProvider(this, true);
        RongIM.setLocationProvider(this);//设置地理位置提供者,不用位置的同学可以注掉此行代码
        setInputProvider();
        setReadReceiptConversationType();
        RongIM.getInstance().enableNewComingMessageIcon(true);
        RongIM.getInstance().enableUnreadMessageIcon(true);
        RongIM.getInstance().setGroupMembersProvider(this);
    }

    private void setReadReceiptConversationType() {
        Conversation.ConversationType[] types = new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.DISCUSSION
        };
        RongIM.getInstance().setReadReceiptConversationTypeList(types);
    }

    private void setInputProvider() {
        RongIM.setOnReceiveMessageListener(this);

        List<IExtensionModule> moduleList = RongExtensionManager.getInstance().getExtensionModules();
        IExtensionModule defaultModule = null;
        if (moduleList != null) {
            for (IExtensionModule module : moduleList) {
                if (module instanceof DefaultExtensionModule) {
                    defaultModule = module;
                    break;
                }
            }
            if (defaultModule != null) {
                RongExtensionManager.getInstance().unregisterExtensionModule(defaultModule);
                RongExtensionManager.getInstance().registerExtensionModule(new SealExtensionModule());
            }
        }
    }

    @Override
    public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String s) {
        return false;
    }

    @Override
    public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String s) {
        return false;
    }

    @Override
    public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) {
        return false;
    }

    @Override
    public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
        MessageContent messageContent = uiConversation.getMessageContent();
        if (messageContent instanceof ContactNotificationMessage) {
            ContactNotificationMessage contactNotificationMessage = (ContactNotificationMessage) messageContent;
            if (contactNotificationMessage.getOperation().equals("AcceptResponse")) {
                // 被加方同意请求后
                if (contactNotificationMessage.getExtra() != null) {
                    ContactNotificationMessageData bean = null;
                    try {
                        JsonUtils.getManager().stringToBean(contactNotificationMessage.getExtra(), ContactNotificationMessageData.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    RongIM.getInstance().startPrivateChat(context, uiConversation.getConversationSenderId(), bean.getSourceUserNickname());

                }
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean onReceived(Message message, int i) {
//        String targetId = message.getTargetId();
//        EventWantChatBean b = new EventWantChatBean();
//        if (WantCHatDBManage.getManage().isInWantChat(mContext, Long.parseLong(targetId))){
//            //是享聊列表来的消息
//            b.setInChat(true);
//        }else {
//            //不是享聊列表来的消息
//            b.setInChat(false);
//        }
//        EventBus.getDefault().post(b);
        return false;
        }


    /**
     * 用户信息提供者的逻辑移到SealUserInfoManager
     * 先从数据库读,没有数据时从网络获取
     */
    @Override
    public UserInfo getUserInfo(String s) {
        UserInfo userInfo = null;
        if (s.equals(String.valueOf(UCommonUtil.getUtil().getId()))){
            //自己
            String headUrl = "";
            if (TextUtils.isEmpty(UChengApplication.userAvatar)){
                headUrl = "http://ucw-user.oss-cn-shanghai.aliyuncs.com/default_image.jpg";
            }else {
                headUrl = UChengApplication.userAvatar;
            }
            userInfo = new UserInfo(String.valueOf(UCommonUtil.getUtil().getId()), UChengApplication.nickName, Uri.parse(headUrl));
        }else {
            //别人
            if (UChengApplication.instance.appActivity.get() ==null){
                Log.d("jjf", "appliactoin地址="+UChengApplication.instance);
                Log.d("jjf", "appActivity地址="+UChengApplication.instance.appActivity.get());
                return null;
            }
            UserBean bean = LoginHttpManager.getManager().checkUserInfo(UChengApplication.instance.appActivity.get(), s);
            if (bean != null){
                String name = "";
                if (!TextUtils.isEmpty(bean.getRemarkName())){
                    name = bean.getRemarkName();
                }else {
                    name = bean.getNickName();
                }
                String headUrl = "";
                if (TextUtils.isEmpty(bean.getUserAvatar())){
                    headUrl = "http://ucw-user.oss-cn-shanghai.aliyuncs.com/default_image.jpg";
                }else {
                    headUrl = bean.getUserAvatar();
                }
                userInfo = new UserInfo(String.valueOf(bean.getId()), name, Uri.parse(headUrl));
            }
        }
        return userInfo;
    }

    @Override
    public Group getGroupInfo(String s) {
        if (UChengApplication.instance.appActivity ==null){
            return null;
        }
        RyGroupBean bean = LoginHttpManager.getManager().checkGroupInfo(UChengApplication.instance.appActivity.get(), s);
        Group group = null;
        if (bean != null){
            group = new Group(String.valueOf(bean.getId()), bean.getGroupName(), Uri.parse(bean.getGroupLogo()));
        }
        return group;
    }

    @Override
    public GroupUserInfo getGroupUserInfo(String groupId, String userId) {
        return null;
    }


    @Override
    public void onStartLocation(Context context, LocationCallback locationCallback) {
        /**
         * demo 代码  开发者需替换成自己的代码。
         */
    }

    /**
     * 聊天界面 用户头像点击事件
     * */
    @Override
    public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
        if (conversationType == Conversation.ConversationType.CUSTOMER_SERVICE || conversationType == Conversation.ConversationType.PUBLIC_SERVICE || conversationType == Conversation.ConversationType.APP_PUBLIC_SERVICE) {
            return false;
        }
        switch (UChengApplication.chatType){
            case 0://普通聊天
                UCommonUtil.getUtil().toUserActivity((Activity) context, Long.parseLong(userInfo.getUserId()));
                break;
            case 1://享聊类型
                Intent intent = null;
                if (userInfo.getUserId().equals(String.valueOf(UCommonUtil.getUtil().getId()))){
                    //点击自己的头像
                    intent = new Intent(mContext, WantMeActivity.class);
                }else {
                    intent = new Intent(mContext, WantChatPersonInfoActivity.class);
                    intent.putExtra(BaseConfig.UID, Long.parseLong(userInfo.getUserId()));
                }
                mContext.startActivity(intent);
                break;
        }

        return true;
    }

    @Override
    public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
        return false;
    }

    @Override
    public boolean onMessageClick(final Context context, final View view, final Message message) {
        /**
         * demo 代码  开发者需替换成自己的代码。
         */
        if (message.getContent() instanceof ImageMessage) {
        }

        return false;
    }

    @Override
    public boolean onMessageLinkClick(Context context, String s) {
        return false;
    }

    @Override
    public boolean onMessageLongClick(Context context, View view, Message message) {
        return false;
    }


    @Override
    public void getGroupMembers(String groupId, final RongIM.IGroupMemberCallback callback) {
    }
}
